package es.albarregas.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.albarregas.modelo.Marca;
import es.albarregas.modelo.ModelFacade;
import es.albarregas.tools.Tools;

/**
 * Servlet implementation class DeleteBrandServlet
 */
@WebServlet("/DeleteBrandServlet")
public class DeleteBrandServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int oid = Integer.parseInt(request.getParameter("brandOid")) ;
		System.out.println("El oid: " +oid);
		if (validar(request)){
			Marca marca = ModelFacade.getMarcaByOid(oid);  // obtengo la marca que se prentende borrar
			if (marca.getnProductos() > 0){
				Tools.aniadirMensaje(request, "La marca elegida contiene productos, no se puede eliminar");
			} else {
				boolean ok = ModelFacade.deleteMarca(oid);
				if (ok){
					Tools.aniadirMensaje(request, "El registro se ha eliminado correctamente");
				}
				else {
					Tools.aniadirMensaje(request, "Error al eliminar el registro");
				}
			}
		}else { // if validar
			response.sendError(404);
		}
		request.getRequestDispatcher("/admin/brands.jsp").forward(request, response); 
	} //doPost

	protected boolean validar(HttpServletRequest request) {
        if (request.getParameterMap().size() >= 1 && request.getParameter("brandOid") != null) {
            return true;
        } else {
            return false;
        }
    }
}
